package com.hrms.realm;

import com.hrms.dao.SysDeptMapper;
import com.hrms.dao.SysUserMapper;
import com.hrms.pojo.SysRole;
import com.hrms.pojo.SysUser;
import com.hrms.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author WCG
 * @version 1.0
 * @date 2021/10/20 19:35
 */
public class MyRealm extends AuthorizingRealm {

	@Autowired(required = false)
	SysUserMapper sysUserMapper;
	//授权
	@Autowired
	SysUserService sysUserService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//获取认证通过的用户名
		Object userName = principals.fromRealm(this.getName()).iterator().next();

		//根据用户名查询用户拥有的角色参数
		List<SysUser> list = sysUserMapper.selectRoleByName(userName + "");

		//创建授权对象
		SimpleAuthorizationInfo smp = new SimpleAuthorizationInfo();
		if (list.size() > 0) {
			//添加角色
			for (SysRole r : list.get(0).getRoleList()) {
				//添加角色参数
				smp.addRole(r.getSysRoleCode());
				System.out.println("给" + userName + "赋予了角色：" + r.getSysRoleName());
			}
		}
		return smp;
	}

	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//取出用户名
		UsernamePasswordToken to = (UsernamePasswordToken) token;
		String userName = to.getPrincipal() + "";
		//验证用户名输入是否正确
		List<SysUser> list = sysUserService.selectByName(userName);
		if (list.size() == 0) {
			throw new UnknownAccountException();
		}
		//创建凭证
		AuthenticationInfo au = new SimpleAuthenticationInfo(
				list.get(0).getUserName(),//用户名
				list.get(0).getUserPwd(),//密码
				new Md5Hash(list.get(0).getSalt()),//加密算法和盐值
				this.getName()//myrealm对象
		);
		return au;


	}
}
